package com.taptech.doufu.ui.fragment;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.MoreAlbumsCottonViewAdapter;
import com.taptech.doufu.bean.AlbumsBean;
import com.taptech.doufu.bean.IconTypeBeans;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.MySwipeRefreshLayout;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.URLParseUtils;
import com.taptech.doufu.net.httputils.HttpResponseObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 漫画分类
 */
public class CartoonSortFragment extends DiaobaoBaseFragment implements HttpResponseListener {
    //part: <1|2|4|5> , 热门｜小说文评｜绘画｜排行版*/
    // 三个方形
    public static final int HOT_ALBMUS = 1;
    // 二个矩形
    public static final int NOVELSWEEP_ALBMUS = 2;
    public static final int DRAW_ALBMUS = 4;
    public static final int RANK_ALBMUS = 5;
    public static final int NOVEL_ALBMUS = 6;
    public static final int COMMON_ALBMUS = 7;
    //推荐小说更多活动专题
    public static final String NOVEL_MORE_ALBMUS = "http://api.doufu.la/index.php/albums/items?id=70";
    private MyRecyclerView recyclerView;
    private MoreAlbumsCottonViewAdapter adapter;
    // 用于下拉刷新
    private MySwipeRefreshLayout swipeRefreshLayout;
    private List<AlbumsBean> mDataList;
    private String last = "";
    private boolean hasMoreContent = true;
    private int page = 0;
    public static int type;
    // 在绘画和小说首页才会有
    private String url;
    private boolean needChangeData = false;
    private View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null){
            rootView = inflater.inflate(R.layout.fragment_cartoon_sort, container, false);
            initWaitWindow();
            initTypeData();
            initView(rootView);
            loadAlbums();
        }
        return rootView;
    }

    private String tempSting;

    @Override
    public void handleResponse(int handleType, final HttpResponseObject response) {
        // TODO Auto-generated method stub
        //再次开启下拉刷新
        swipeRefreshLayout.isRefreshing();
        //隐藏顶部视图
        // adapter.setHeadViewVisible(View.GONE);

        if (response == null) {
            UIUtil.toastMessage(getActivity(), Constant.loadingFail);
            return;
        }
        switch (handleType) {
            case HomeMainServices.HANDLE_TYPE_LOAD_MORE_ALBUMS:
                if (hasMoreContent) {
                    JSONObject data = (JSONObject) response.getData();
                    try {
                        List<AlbumsBean> dataList = DiaobaoUtil.json2list(AlbumsBean.class, data.getJSONArray("albums"));
                        if (dataList == null || dataList.size() <= 0) {
                            //数据为空
                            hasMoreContent = false;
                            recyclerView.setLoadMoreEnable(false);
                        } else {
                            //正常加载数据
                            hasMoreContent = true;
                            recyclerView.setLoadMoreEnable(true);
                            if (page == 0) {
                                mDataList.clear();
                            }
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                        }
                        page = page + 1;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case HomeMainServices.HANDLE_TYPE_LOAD_ALBUMS:
                JSONObject data = null;
                tempSting = URLParseUtils.parseA(url);
                if (response.getStatus() == Constant.STATUS_SUCCESS) {
                    if ((last == null) || (last.equals(""))) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                            }
                        }).start();
                    }
                    data = (JSONObject) response.getData();
                } else {
                    //加载缓存
                    UIUtil.toastMessage(getActivity(), DiaobaoUtil.getErrorTips(response));
                    if ((last == null) || (last.equals(""))) {
                        data = CacheUtil.readJsonDataFromCache(new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                    }
                }


                if (hasMoreContent) {
                    try {
                        List<AlbumsBean> dataList = new ArrayList<AlbumsBean>();
                        if (needChangeData) {
                            List<IconTypeBeans> iconBeans = com.alibaba.fastjson.JSONArray.parseArray(data.getJSONArray("list").toString(), IconTypeBeans.class);
                            if ((iconBeans != null) && (iconBeans.size() > 0)) {
                                for (int i = 0; i < iconBeans.size(); i++) {
                                    AlbumsBean tempAlbumsBean = new AlbumsBean();
                                    tempAlbumsBean.setName(iconBeans.get(i).getTitle());
                                    tempAlbumsBean.setCover(iconBeans.get(i).getImgUrl());
                                    tempAlbumsBean.setIcon(iconBeans.get(i).getImgUrl());
                                    if (iconBeans.get(i).getUrl().contains("?")) {
                                        tempAlbumsBean.setUrl(iconBeans.get(i).getUrl());
                                    } else {
                                        tempAlbumsBean.setUrl(iconBeans.get(i).getUrl() + "?");
                                    }
                                    dataList.add(tempAlbumsBean);
                                }
                            }
                        } else {
                            dataList = DiaobaoUtil.json2list(AlbumsBean.class, data.getJSONArray("items"));
                        }

                        if (last.equals("")) {
                            //正常加载数据
                            hasMoreContent = true;
                            recyclerView.setLoadMoreEnable(true);
                            mDataList.clear();
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                        } else if (!last.equals(data.getString("last"))) {
                            hasMoreContent = true;
                            recyclerView.setLoadMoreEnable(true);
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                        } else {
                            hasMoreContent = false;
                            recyclerView.setLoadMoreEnable(false);

                        }
                        last = data.getString("last");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }


    }

    private void initTypeData() {
        needChangeData = true;
        type = 4;
        url = "http://api.doufu.la/index.php/entrance_item/comic_category?begin=0&last=&lastStart=0&rows=0&size=20&start=0";
        mDataList = new ArrayList<AlbumsBean>();
    }

    RecyclerView.LayoutManager layoutManager;

    private void initView(View view) {
        swipeRefreshLayout = (MySwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        recyclerView = (MyRecyclerView) view.findViewById(R.id.albmus_gridview);
        layoutManager = new GridLayoutManager(getActivity(), type == HOT_ALBMUS ? 2 : 3);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MoreAlbumsCottonViewAdapter(getActivity(), mDataList);
        //adapter.setHeaderView(R.layout.recyclerview_pull_headview);

        recyclerView.setAdapter(adapter);
        recyclerView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener() {
            @Override
            public void loadMore() {
                loadMoreAlbmus();
            }
        });
        recyclerView.setOnScrollToTopListener(new MyRecyclerView.OnScrollToTopListener() {
            @Override
            public void refresh() {
                if (!adapter.isHeadViewVisible())
                    swipeRefreshLayout.setEnabled(false);
            }

            @Override
            public void notAtTopInScrollView(int offsetY, int directionY) {
                swipeRefreshLayout.setEnabled(false);
            }
        });
        swipeRefreshLayout.setEnabled(false);
        //swipeRefreshLayout.setmProgressDrawable(getResources().getDrawable(R.drawable.ic_launcher));
        //刷新动画
        swipeRefreshLayout.setSize(0);

    }

    private synchronized void loadAlbums() {
        if (mDataList != null) {
            page = 0;
            hasMoreContent = true;

            if (url != null) {
                HomeMainServices.getInstance().loadAlbumsList(this, url, last);
            } else {
                HomeMainServices.getInstance().loadMoreAlbums(type + "", Constant.PAGE_SIZE_12, page, this);
            }
        }
    }

    private synchronized void loadMoreAlbmus() {
        if (hasMoreContent) {


            if (url != null) {
                HomeMainServices.getInstance().loadAlbumsList(this, url, last);
            } else {

                HomeMainServices.getInstance().loadMoreAlbums(type + "", Constant.PAGE_SIZE_12, page, this);
            }
        }
    }

    private void initWaitWindow() {

    }
}
